package com.ftwj.config.resp;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;

/**
 * 接口数据返回包装类型
 * @author spring
 * @date 2020/12/14 15:47
 */
public class ResultMessage<T> implements Serializable {

    private static final long serialVersionUID = 997541448947743419L;

    /**
     * 响应业务状态码
     */
    private String code;

    /**
     * 响应消息内容
     */
    private String msg;

    /**
     * 响应数据内容
      */
    private T data;

    /**
     * 响应时间
     */
    private Date timestamp;

    /**
     * 数据是否加密：默认为否
     */
    private boolean encrypt = false;

    public static ResultMessage success() {
        return new ResultMessage(ErrorCodeEnum.SUCCESS);
    }

    public static ResultMessage success(Object data) {
        return new ResultMessage(ErrorCodeEnum.SUCCESS, data);
    }

    public static ResultMessage error() {
        return new ResultMessage(ErrorCodeEnum.SYSTEM_ERROR_RUN_EXCEPTION);
    }

    public ResultMessage(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.timestamp = new Date();
    }

    public ResultMessage(IResponseCode errorCode) {
        this.code = errorCode.getCode();
        this.msg = errorCode.getDescription();
        this.timestamp = new Date();
    }

    public ResultMessage(IResponseCode errorCode, T data) {
        this.code = errorCode.getCode();
        this.msg = errorCode.getDescription();
        this.data = data;
        this.timestamp = new Date();
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public ResultMessage setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public T getData() {
        return data;
    }

    public ResultMessage setData(T data) {
        this.data = data;
        return this;
    }

    /**
     * 以map方式存储数据
     */
    public ResultMessage putData(String key, Object value) {
        HashMap<String, Object> temp;
        if (data == null || (data instanceof HashMap) == false) {
            temp = new HashMap<>(16);
        } else {
            temp = (HashMap) data;
        }
        temp.put(key, value);
        this.data = (T) temp;
        return this;
    }

    public void setEncrypt(boolean encrypt) {
        this.encrypt = encrypt;
    }

}
